import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron'
import path from 'path'

function dowlandUpdate(mainWindow: BrowserWindow) {
  mainWindow.webContents.on('will-navigate', (event, url) => {
    if (url.startsWith('http://') || url.startsWith('https://')) {
      event.preventDefault() // 阻止页面跳转
      console.log(url)
    }
  })
  // 页面调用这个方法
  ipcMain.handle('start-download', (event, msg) => {
    mainWindow.webContents.downloadURL(msg.downloadUrL)
    mainWindow.webContents.session.on('will-download', (event, item) => {
      //   将文件保存在系统的下载目录
      const filePath = path.join(app.getPath('downloads'), item.getFilename())
      // 自动保存
      item.setSavePath(filePath)
      // 下载进度
      item.on('updated', (event, state) => {
        switch (state) {
          case 'progressing':
            mainWindow.webContents.send(
              'pc-update-progress',
              ((item.getReceivedBytes() / item.getTotalBytes()) * 100).toFixed(0)
            )
            break
          case 'interrupted':
            mainWindow.webContents.send('download-paused', true)
            break
          default:
            break
        }
      })
      // 下载完成或失败
      item.once('done', (event, state) => {
        switch (state) {
          case 'completed':
            console.log(state)
            // const ceshi = shell.openPath(filePath)
            shell.openPath(filePath)
            // mainWindow.webContents.send("download-done", data);
            break
          case 'interrupted':
            mainWindow.webContents.send('download-error', true)
            dialog.showErrorBox(
              '下载出错',
              '由于网络或其他未知原因导致客户端下载出错，请前往官网进行重新安装'
            )
            break
          default:
            break
        }
      })
    })
  })
}
export default dowlandUpdate
